package com.scpii.universal.concurrent.service;

import java.io.File;
import java.io.PrintStream;

import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scpii.universal.concurrent.task.TaskMsg;
import com.scpii.universal.pb.UniversalProtocol.FinishTaskCS;
import com.scpii.universal.pb.UniversalProtocol.TaskSC;

public class LocalCompileService {

	private static final Logger logger = LoggerFactory
			.getLogger(LocalCompileService.class);

	private static final String RELATIVELY_PATH = System
			.getProperty("user.dir");

	public static void deal(final TaskSC task, final TaskMsg msg) {
		String configName = task.getConfigName();
		String appSign = task.getAppSign();
		String appName = task.getAppName();

		File buildFile = new File(RELATIVELY_PATH + File.separator + "config"
				+ File.separator + "build.xml");
		Project p = new Project();
		DefaultLogger consoleLogger = new DefaultLogger() {
			@Override
			public void buildFinished(BuildEvent event) {
				super.buildFinished(event);
				FinishTaskCS.Builder builder = FinishTaskCS.newBuilder();
				builder.setTaskID(task.getTaskID());
				if (event.getException() != null
						&& event.getException() instanceof BuildException) {
					builder.setOpCode(1);
				} else {
					builder.setOpCode(0);
					builder.setFileName(task.getConfigName() + ".apk");
				}
				msg.mCallback.handleMessage(msg.action, builder.build()
						.toByteArray());
			}

			@Override
			protected void log(String message) {
				logger.info(message);
			}

			@Override
			protected void printMessage(String message, PrintStream stream,
					int priority) {
			}
		};
		consoleLogger.setMessageOutputLevel(Project.MSG_INFO);

		p.addBuildListener(consoleLogger);

		try {
			p.fireBuildStarted();
			p.setProperty("configName", configName);
			p.setProperty("appSign", appSign);
			p.setProperty("appName", appName);
			p.init();
			ProjectHelper.configureProject(p, buildFile);
			p.executeTarget(p.getDefaultTarget());
			p.fireBuildFinished(null);
		} catch (BuildException e) {
			p.fireBuildFinished(e);
		}
	}
}
